package com.astn.bks;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import com.astn.bks.util.BksConstants;
import com.astn.bks.util.WebserviceUtils;
import com.astn.payment.paypal.AstnPayPalPayment;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalInvoiceData;
import com.paypal.android.MEP.PayPalInvoiceItem;
import com.paypal.android.MEP.PayPalPayment;

import adstn.dialoglib.Dialog;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.Toast;

public class CPayment extends Activity {
	private static final int INITIAL_SUCCESS = 1;
	private static final int INITIAL_FAIL = 0;
	private LinearLayout layContent;
	private LinearLayout layLoading;
	private LinearLayout layButton;
	private AstnPayPalPayment payment;
	private CheckoutButton btnPaypalSimpleCheckout;
	private JsonObject jsonOffer;
	private Handler refreshView = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case INITIAL_SUCCESS:
				setupButton();
				break;
			case INITIAL_FAIL:
				showFailure();
				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LayoutInflater lInflater = LayoutInflater.from(this);
		View mainView = lInflater.inflate(R.layout.cpayment, null);
		layContent = (LinearLayout) mainView.findViewById(R.id.layContent);
		View loadingView = lInflater.inflate(R.layout.cpaymentloading, null);
		layContent.addView(loadingView);
		setContentView(mainView);
		Thread initialLibraryThread = new Thread() {

			@Override
			public void run() {
				payment = new AstnPayPalPayment(CPayment.this);
				if (payment.getInitialStatus() == AstnPayPalPayment.INITIAL_SUCCESS) {
					refreshView.sendEmptyMessage(INITIAL_SUCCESS);
				} else {
					refreshView.sendEmptyMessage(INITIAL_FAIL);
				}

			}

		};
		initialLibraryThread.start();

	}

	private void setupButton() {
		LayoutInflater lInflater = LayoutInflater.from(this);
		View paymentView = lInflater.inflate(R.layout.cpaymentbutton, null);
		layButton = (LinearLayout) paymentView.findViewById(R.id.layPayPal);
		btnPaypalSimpleCheckout = payment.getPaypal().getCheckoutButton(this,
				PayPal.BUTTON_152x33, CheckoutButton.TEXT_PAY);
		layButton.addView(btnPaypalSimpleCheckout);
		layContent.removeAllViews();
		layContent.addView(paymentView);
		btnPaypalSimpleCheckout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				PayPalPayment payment = new PayPalPayment();
				// Sets the currency type for this payment.
				payment.setCurrencyType("USD");
				// Sets the recipient for the payment. This can also be a phone
				// number.
				// Get recipient infomation from server.
				Map<String, Object> mapPara = new HashMap<String, Object>();
				int recipientid = jsonOffer.get("fromUser").getAsJsonObject()
						.get("id").getAsInt();
				mapPara.put("RECIPEINTID", recipientid);
				Object rsObj = null;
				try {
					rsObj = WebserviceUtils.call("com_xmlrpc",
							"getRecipientEmail", mapPara);
				} catch (Exception e) {
					// TODO: handle exception
				}
				if (rsObj == null || rsObj.toString().trim().length() == 0) {
					Toast.makeText(CPayment.this,
							"Get recipeint infomation error.",
							Toast.LENGTH_SHORT).show();
					setResult(BksConstants.RESULT_ERROR);
					finish();
				}
				payment.setRecipient(rsObj.toString());
				// Sets the amount of the payment, not including tax and
				// shipping amounts.
				payment.setSubtotal(jsonOffer.get("price").getAsBigDecimal());
				// Sets the payment type. This can be PAYMENT_TYPE_GOODS,
				// PAYMENT_TYPE_SERVICE, PAYMENT_TYPE_PERSONAL, or
				// PAYMENT_TYPE_NONE.
				payment.setPaymentType(PayPal.PAYMENT_TYPE_SERVICE);

				// PayPalInvoiceData can contain tax and shipping amounts. It
				// also contains an ArrayList of PayPalInvoiceItem which can
				// be filled out. These are not required for any transaction.
				PayPalInvoiceData invoice = new PayPalInvoiceData();
				// Sets the tax amount.
				invoice.setTax(new BigDecimal("0"));
				// Sets the shipping amount.
				invoice.setShipping(new BigDecimal("0"));

				// PayPalInvoiceItem has several parameters available to it.
				// None of these parameters is required.
				PayPalInvoiceItem item1 = new PayPalInvoiceItem();
				// Sets the name of the item.

				item1.setName("Hotel service");
				// Sets the ID. This is any ID that you would like to have
				// associated with the item.
				item1.setID(jsonOffer.get("id").getAsString());
				// Sets the total price which should be (quantity * unit price).
				// The total prices of all PayPalInvoiceItem should add up
				// to less than or equal the subtotal of the payment.
				item1.setTotalPrice(jsonOffer.get("price").getAsBigDecimal());
				// Sets the unit price.
				item1.setUnitPrice(jsonOffer.get("price").getAsBigDecimal());
				// Sets the quantity.
				item1.setQuantity(1);
				// Add the PayPalInvoiceItem to the PayPalInvoiceData.
				// Alternatively, you can create an ArrayList<PayPalInvoiceItem>
				// and pass it to the PayPalInvoiceData function
				// setInvoiceItems().
				invoice.getInvoiceItems().add(item1);

				// Sets the PayPalPayment invoice data.
				payment.setInvoiceData(invoice);
				// Sets the merchant name. This is the name of your Application
				// or Company.
				payment.setMerchantName("VQuote booking system");
				// Sets the description of the payment.
				// About the service
				String dsc = "";
				int star = (new Float(jsonOffer.get("star").getAsFloat()))
						.intValue();
				String roomtype = jsonOffer.get("roomtype").getAsJsonObject()
						.get("roomtypename").getAsString();
				String beds = jsonOffer.get("beds").toString();
				String facilites = "";
				JsonArray jarFacilities = null;
				try {
					jarFacilities = jsonOffer.get("facilities")
							.getAsJsonArray();
				} catch (Exception e) {
				}
				if (jarFacilities != null) {
					for (int i = 0; i < jarFacilities.size(); i++) {
						facilites += jarFacilities.get(i).getAsJsonObject()
								.get("facilityname").getAsString();
						if (i < jarFacilities.size() - 1) {
							facilites += ", ";
						}
					}
				}
				dsc = String.valueOf(star) + " star(s), roomtype: " + roomtype
						+ ", beds: " + beds + ", Facilities: " + facilites;
				payment.setDescription(dsc);
				// Sets the Custom ID. This is any ID that you would like to
				// have associated with the payment.
				payment.setCustomID(jsonOffer.get("toUserId").getAsString());
				// Sets the Instant Payment Notification url. This url will be
				// hit by the PayPal server upon completion of the payment.
				payment.setIpnUrl("http://vigentocommerce.net/projects/quote/");
				// Sets the memo. This memo will be part of the notification
				// sent by PayPal to the necessary parties.
				payment.setMemo("");
				Intent checkoutIntent = PayPal.getInstance().checkout(payment,
						CPayment.this, new PayPalDelegate(CPayment.this));
				startActivityForResult(checkoutIntent,
						BksConstants.REQUEST_PAYPAL_CHECKOUT);

			}

		});
	}

	private void showFailure() {
		LayoutInflater lInflater = LayoutInflater.from(this);
		View failureView = lInflater.inflate(R.layout.cpaymentfailure, null);
		layContent.removeAllViews();
		layContent.addView(failureView);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case BksConstants.REQUEST_PAYPAL_CHECKOUT:
			switch (resultCode) {
			case RESULT_OK:
				String payKey = data.getStringExtra(BksConstants.EXTRA_PAYKEY);
				Dialog.showAlert(this, "Payment success with paykey: " + payKey);
				
				break;

			default:
				break;
			}
			break;

		default:
			break;
		}
	}

}
